import { ActorEnum } from './../../../../libs/db/src/entity/enum/actor.enum';
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { Logger } from 'libs/db/entity/logger.entity';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LoggerService } from '../_logger/logger.service';
import { HandleStatus } from '../../../../libs/db/src/entity/enum/handle-status.enum';
import { moduleLoggerInfo } from '../_decorator/logger-info';
import { HandleMoudle } from 'libs/db/entity/enum/handle-module.enum';

class logMessage {
  //模块 名称
  name: string
  //开发 信息（系统审计）
  devMessage: string
  //用户 信息（日志）
  userMessage: string
}

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  constructor(private readonly _logger: LoggerService, private reflector: Reflector) {
    
  }
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    const req : Request = context.switchToHttp().getRequest<Request>()

    const loggerInfo = this.reflector.get<moduleLoggerInfo>('loggerInfo', context.getHandler())

    console.log(loggerInfo)

    this._logger.debug( `controller ${context.getClass().name} - method ${context.getHandler().name}`, `进入 拦截器`)

    if(loggerInfo) {
      this._logger._log( 
        `controller ${context.getClass().name} - method ${context.getHandler().name}`, 
        `进入 拦截器`, 
        new Logger(req, context.getHandler().name, loggerInfo.handleName, loggerInfo.handleStatus, HandleMoudle[context.getClass().name], ActorEnum.villager),
      )
    }  
    
    this._logger.debug(
      `请求 { ${req.path}, 
      ${req.method} } route  将要执行 ${context.getHandler().name}`, 
      `${context.getClass().name}`
    )

    return next
      .handle()
      .pipe(
        tap(
          (res) =>
          this._logger.log(`controller ${context.getClass().name} - method ${context.getHandler().name} - res 请求到的数据长度 ${res.length}`, `出去 拦截器`)
        )
      );
  }
}